//var time = sessionStorage.obj;
//var today;
//if (typeof (time) == "undefined") {
//	var today = new Date();
//	today.setHours(0, 0, 0, 0);
//} else {
//	// 重新转换为对象
//	obj = JSON.parse(time);
//	today = new Date(obj.name);
//}
//showTime();
//function showTime() {
//	var second = today.getSeconds() + 1;
//	today.setSeconds(second, 0);
//	var timeTick = today.getHours() + "小时" + today.getMinutes() + "分钟"
//			+ today.getSeconds() + "秒";
//	$("#timeTick").text(timeTick);
//	window.setTimeout("showTime()", 1000);
//}
//window.onbeforeunload = function(event) {
//	var timelong = today.getTime();
//	var obj = {
//		name : timelong
//	};
//	var str = JSON.stringify(obj);
//	sessionStorage.obj = str;
//}

var time = sessionStorage.time;
var obj = JSON.parse(time);
showTime();
function showTime() {
	$("#timeTick").text(betwDaysStr(obj.timebegin));
	window.setTimeout("showTime()", 1000);
}

function betwDaysStr(beginTime) {
	var betwwen = "";
	var today = new Date().getTime();
	var nTime = today - parseInt(beginTime);
	// 计算相差的月数
	var leave = nTime % (12 * 30 * 24 * 3600 * 1000);
	var months = Math.floor(leave / (30 * 24 * 3600 * 1000));
	// 计算出相差天数
	var leave0 = leave % (30 * 24 * 3600 * 1000);
	var days = Math.floor(leave0 / (24 * 3600 * 1000));
	// 计算出小时数
	var leave1 = leave0 % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	// 计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));
	// 计算相差秒数
	var leave3 = leave2 % (60 * 1000); // 计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	hours = days * 24 + hours;
	betwwen += hours + "小时" + minutes + "分钟" + seconds + "秒";
	return betwwen;
}

var service = new EbeimService();
var jchartCpu = $("#j-chartCpu");
var jchartMenory = $("#j-chartMenory");
var jlist = $("#j-list");
var netWorkRest = $("#netWorkRest");
var $rateCpu = 0;
var $rateMem = 0;
var tpl;

$(function() {
	var json = {};
	service.getMonitor(json, callback);
	Highcharts.setOptions({
		global : {
			useUTC : false
		}
	});
	var call = function(data) {
		$rateCpu = parseFloat(data.cpuRate);
		$rateMem = parseFloat(data.memRate);
	}
	var chart;
	var user = plugin.cookieToJson(document.cookie);
	var jusername = $("#j-username"), jrole = $("#j-role");

	jusername.html(user.username);
	if (user.role == "SYSADMIN") {
		jrole.html("系统管理员");
	} else if (user.role == "ADMIN") {
		jrole.html("管理员");
	} else {
		jrole.html("普通用户");
	}
	jchartCpu.highcharts({
		chart : {
			type : 'spline',
			animation : Highcharts.svg, // don't animate in old IE
			marginRight : 10,
			events : {
				load : function() {
					var series = this.series[0];
					setInterval(function() {
						var service = new EbeimService();
						var json = {};
						service.getCpuRate(json, call);
						var x = (new Date()).getTime(), // current time
						y = $rateCpu;
						series.addPoint([ x, y ], true, true);

					}, 5000);
				}
			}
		},
		title : {
			text : ''
		},
		xAxis : {
			type : 'datetime',
			tickPixelInterval : 150
		},
		yAxis : {
			title : {
				text : ''
			},
			plotLines : [ {
				value : 0,
				width : 1,
				color : '#808080'
			} ]
		},
		credits : {
			text : '',
			href : ''
		},
		tooltip : {
			formatter : function() {
				return '<b>' + this.series.name + '</b><br>'
						+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)
						+ '<br>' + Highcharts.numberFormat(this.y, 2);
			}
		},
		legend : {
			enabled : false
		},
		exporting : {
			enabled : false
		},
		series : [ {
			name : 'cpu使用率',
			data : (function() {
				// generate an array of random data
				var data = [], time = (new Date()).getTime(), i;

				for (i = -19; i <= 0; i++) {
					data.push({
						x : time + i * 1000,
						y : 0
					});
				}
				return data;
			})()
		} ]
	});

	jchartMenory.highcharts({
		chart : {
			type : 'spline',
			animation : Highcharts.svg, // don't animate in old IE
			marginRight : 10,
			events : {
				load : function() {
					var series = this.series[0];
					setInterval(function() {
						var service = new EbeimService();
						var json = {};
						service.getCpuRate(json, call);
						var x = (new Date()).getTime(), // current time
						y = $rateMem;
						series.addPoint([ x, y ], true, true);
					}, 5000);
				}
			}
		},
		title : {
			text : ''
		},
		xAxis : {
			type : 'datetime',
			tickPixelInterval : 150
		},
		yAxis : {
			title : {
				text : ''
			},
			plotLines : [ {
				value : 0,
				width : 1,
				color : '#808080'
			} ]
		},
		credits : {
			text : '',
			href : ''
		},
		tooltip : {
			formatter : function() {
				return '<b>' + this.series.name + '</b><br>'
						+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)
						+ '<br>' + Highcharts.numberFormat(this.y, 2);
			}
		},
		legend : {
			enabled : false
		},
		exporting : {
			enabled : false
		},
		series : [ {
			name : '物理内存',
			data : (function() {
				// generate an array of random data
				var data = [], time = (new Date()).getTime(), i;

				for (i = -19; i <= 0; i++) {
					data.push({
						x : time + i * 1000,
						y : 0
					});
				}
				return data;
			})()
		} ]
	});

	// 网络监控列表
	tpl = (function() {
		var tpl = {};
		$("script[type='text/ysmart']").each(function() {
			var t = $(this);
			tpl[t.attr("data-name")] = t.html();
		});
		return tpl;
	})();
	getList();
	setInterval(function() {
		getList();
	}, 1000 * 60);

	netWorkRest.click(function() {
		getList();
	})
})
function callback(data) {
	if (data.code == 200) {
		var space = data.statics;
		$("#save_space").text(
				fileSizeTransferNoPoint(space.usageSize) + "/"
						+ fileSizeTransferNoPoint(space.countSize));
		$("#server_endTime").text(getTime(data.serverInfo.endTime));
		$("#bindDevice").text(data.bindDevice);
		$("#bindDeviceName").text(data.bindDeviceName);
		$("#netcircums").text(data.netcircums);
		$("#mem").text(data.mem);
		$("#systemOpt").text(data.systemOpt);
		$("#processor").text(data.processor);
		autoStart(data.serviceInfo.autoStart, data.serviceInfo.exit);
		autoUpadate(data.serviceInfo.autoUpdate, data.serviceInfo.exit);
		serviceInfo(data.serviceInfo.exit);
		// if (data.serviceInfo.exit == 0) {
		// $("#stop").addClass("unstop-btn").removeAttr("onclick");
		// }
	} else {
		alert("请求出错！");
	}
}
// 定时扫描任务
tick();
function tick() {
	getServerStatus();
	window.setTimeout("tick()", 3000);
}
function getServerStatus() {
	var json = {};
	service.getServiceStatus(json, serverStatusCallback);
}
function serverStatusCallback(data) {
	if (data.code == 200) {
		autoStart(data.serviceInfo.autoStart, data.serviceInfo.exit);
		autoUpadate(data.serviceInfo.autoUpdate, data.serviceInfo.exit);
		serviceInfo(data.serviceInfo.exit);
//		if (data.serviceInfo.exit == 0) {
//			$("#stop").addClass("unstop-btn").removeAttr("onclick");
//		} else {
//			$("#stop").removeClass("unstop-btn").attr("onclick", "stop()");
//		}
	} else {
		plugin.msgtip({
			type : "e",
			msg : "服务配置文件请求出错！"
		});
	}
}

function changeAutoupdate(status, serName) {
	// 点击之后改变状态；
	var service = new EbeimService();
	var json = {};
	if (status == 1) {
		status = 0;
	} else {
		status = 1;
	}
	json.name = serName;
	json.status = status;
	service.changeServiceParam(json, changeCallback);

}
function serviceInfo(run) {
	if (run == 0) {
		$("#service").html("监控服务（停止）").attr("class", "red btn");
	} else {
		$("#service").html("监控服务（运行中）").attr("class", "blue btn");
	}
	$("#service").attr("onclick", "javascript:changeService('" + run + "')");
}
function changeService(status) {
	var service = new EbeimService();
	service.changeService({
		status : status
	}, function(data) {
		if (data.code == 200) {
			serviceInfo(data.status);
			getServerStatus();
			plugin.msgtip({
				type : "o",
				msg : "设置成功！"
			});
		} else {
			plugin.msgtip({
				type : "e",
				msg : "请求出错！"
			});
		}
	});
}

function autoStart(status, run) {
	if (run == 0) {
		$("#autoStart").html("数据保险箱引擎（停止）");
		$("#autoStart").attr("class", "red btn");
		$("#autoStart").removeAttr("onclick",
				"javascript:changeAutoupdate('" + status + "','AutoStart')");

	} else {
		if (status == 1) {
			$("#autoStart").html("数据保险箱引擎（运行中）");
			$("#autoStart").attr("class", "blue btn");
		} else {
			$("#autoStart").html("数据保险箱引擎（停止）");
			$("#autoStart").attr("class", "red btn");
		}
		$("#autoStart").attr("onclick",
				"javascript:changeAutoupdate('" + status + "','AutoStart')");

	}
}

function autoUpadate(status, run) {
	if (run == 0) {
		$("#autoUpdate").html("自动更新服务（停止）");
		$("#autoUpdate").attr("class", "red btn");
		$("#autoUpdate").removeAttr("onclick",
				"javascript:changeAutoupdate('" + status + "','AutoUpdate')");
	} else {
		if (status == 1) {
			$("#autoUpdate").html("自动更新服务（启动中）");
			$("#autoUpdate").attr("class", "blue btn");
		} else {
			$("#autoUpdate").html("自动更新服务（停止）");
			$("#autoUpdate").attr("class", "red btn");
		}
		$("#autoUpdate").attr("onclick",
				"javascript:changeAutoupdate('" + status + "','AutoUpdate')");
	}
}

function changeCallback(data) {

	var status = data.status;
	if (data.tagName == 'AutoStart') {
		autoStart(status);
	} else {
		autoUpadate(status);
	}
	if (data.code == "200" || data.code == 200) {
		plugin.msgtip({
			type : "o",
			msg : "设置成功！"
		});
	} else {
		plugin.msgtip({
			type : "e",
			msg : "设置出错！"
		});

	}
}

function getTime(nS) {
	var mm = nS.split(" ");
	mm[0].replace(/-/g, '/');
	return mm[0];
}

var getList = function() {

	service.getMonitorNetWorkMonitor("", function(json) {
		if (json.code != 200) {
			// plugin.msgtip({type: "i",msg: json.message});
			// jlist.html("");
			return false;
		}
		// for(var i in json){
		// json[i].fileSize = fileSizeTransfer(json[i].fileSize);
		// json[i].dsId = searchVar.dsId;
		// json[i].version = searchVar.version;
		// /*json[i].path = json[i].path.split("\\").join("\\\\");*/
		// }
		jlist.html(plugin.ysmart(tpl.list, json.list));
	});
}
//function stop(stopobj) {
//	service.monitorStopService("", function(json) {
//		if (json.code == 200) {
//			plugin.msgtip({
//				type : "o",
//				msg : "停止服务成功！"
//			});
//			$("#stop").addClass("unstop-btn").removeAttr("onclick");
//		} else {
//			plugin.msgtip({
//				type : "e",
//				msg : "系统出错！"
//			});
//		}
//
//	})
//}
